//
//  UIViewController+MyUtil.m
// jqb_v2
//
//  Created by dev on 14-7-9.
//  Copyright (c) 2014年 EFunds. All rights reserved.
//

#import "UIViewController+MyUtil.h"
#import "BDKNotifyHUD.h"

#define TOASTVIEWTAG 10000

#define DEFAULT_TOAST_DURATION 3.0

@interface UIView(MyUtil)

- (UIView *)leve1SubViewWithTag:(NSInteger)tag;


@end

@implementation UIView(MyUtil)

- (UIView *)leve1SubViewWithTag:(NSInteger)tag
{
    __block UIView *toastView = nil;
    [[self subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if([(UIView *)obj tag] == tag){
            toastView = (UIView *)obj;
            *stop = YES;
        }
    }];
    return toastView;
}

- (void)forceHideToast
{
    UIView *toastView = [self leve1SubViewWithTag:TOASTVIEWTAG];
    
    if (toastView && [toastView isKindOfClass:[BDKNotifyHUD class]]) {
        @try {
            [toastView removeFromSuperview];
        }
        @catch (NSException *exception) {
            
        }
        return;
    }
}


@end

@implementation UIViewController (MyUtil)


/**
 *@brief 弹出对话框
 */
- (void)showAlertMsg:(NSString *)msg
{
    [self showAlertWithTitle:nil msg:msg];
}

- (void)showAlertWithTitle:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

- (void)showToast:(NSString *)toast
{
    [self showToast:toast inWindow:YES];
}

- (void)showToast:(NSString *)toast inWindow:(BOOL)inWindos
{
    [self showToast:toast duration:DEFAULT_TOAST_DURATION inWindow:inWindos];
}

- (void)showToast:(NSString *)toast duration:(CGFloat)dur
{
    [self showToast:toast duration:dur inWindow:YES];
}

+ (UIView *)getLeve1SubViewWithParentView:(UIView *)parentView tag:(NSInteger)tag
{
    __block UIView *toastView = nil;
    [[parentView subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if([(UIView *)obj tag] == tag){
            toastView = (UIView *)obj;
            *stop = YES;
        }
    }];
    return toastView;
}

/**
 *  toast
 *
 *  @param toast 提示信息内容
 *  @param dur   显示的持续时间
 */
- (void)showToast:(NSString *)toast duration:(CGFloat)dur inWindow:(BOOL)inWindow
{
    UIView *containerView = nil;
    if (inWindow) {
        containerView = [[UIApplication sharedApplication] keyWindow];
    }
    else {
        containerView = self.view;
    }
    
    UIView *toastView = [UIViewController getLeve1SubViewWithParentView:containerView tag:TOASTVIEWTAG];
    
    if (toastView && [toastView isKindOfClass:[BDKNotifyHUD class]] && [(BDKNotifyHUD *)toastView isAnimating]) {
        return;
    }
    
    if (inWindow) {
        [NSObject cancelPreviousPerformRequestsWithTarget:containerView selector:@selector(forceHideToast) object:nil];
    }
    
    BDKNotifyHUD *notify = [BDKNotifyHUD notifyHUDWithView:nil text:toast];
    notify.center = CGPointMake(self.view.center.x, self.view.center.y);
    notify.tag = TOASTVIEWTAG;
    
    [containerView addSubview:notify];
    [notify presentWithDuration:dur speed:0.38 inView:containerView completion:^(){
        [notify removeFromSuperview];
        if (inWindow) {
            [NSObject cancelPreviousPerformRequestsWithTarget:containerView selector:@selector(forceHideToast) object:nil];
        }
    }];
    
    
    //由于BDKNotifyHUD存在presentWithDuration不执行complection的情况，需要强行关闭toast（看门狗）
    if (inWindow) {
        [containerView performSelector:@selector(forceHideToast) withObject:nil afterDelay:1];
    }
}



/**
 *  支持执行block的toast
 *
 *  @param toast      提示信息内容
 *  @param dur        显示的持续时间
 *  @param completion 需要执行的block
 */
- (void)showToast:(NSString *)toast
         duration:(CGFloat)dur
  completionBlack:(void (^)(void))completion
{
    UIView *containerView = nil;
    containerView = [[UIApplication sharedApplication] keyWindow];
    
    UIView *toastView = [containerView leve1SubViewWithTag:TOASTVIEWTAG];
    
    if (toastView && [toastView isKindOfClass:[BDKNotifyHUD class]] && [(BDKNotifyHUD *)toastView isAnimating]) {
        return;
    }
    
    BDKNotifyHUD *notify = [BDKNotifyHUD notifyHUDWithView:nil text:toast];
    notify.center = CGPointMake(self.view.center.x, self.view.center.y);
    notify.tag = TOASTVIEWTAG;
    [[[[UIApplication sharedApplication] delegate] window] addSubview:notify];
    
    [notify presentWithDuration:dur speed:0.38 inView:containerView completion:^(){
        [notify removeFromSuperview];
        if (completion) {
            completion();
        }
    }];
}

- (void)showProcessHUD:(NSString *)text
{
    if ([self isKindOfClass:[UINavigationController class]]||self.tabBarController) {
        [MBProgressHUD showHUDAddedTo:self.view text:text animated:YES];
    }
    else if(self.navigationController){
        [MBProgressHUD showHUDAddedTo:self.navigationController.view text:text animated:YES];
    }
}

-(void)showProcessHUD:(NSString *)text inView:(UIView *)view
{
    [MBProgressHUD showHUDAddedTo:view text:text animated:YES];
}

- (void)showProcessHUD:(NSString *)text completionBlock:(void (^)(void))completion
{
    if ([self isKindOfClass:[UINavigationController class]]||self.tabBarController) {
        [MBProgressHUD showHUDAddedTo:self.view text:text animated:YES];
    }
    else if(self.navigationController){
        [MBProgressHUD showHUDAddedTo:self.navigationController.view text:text animated:YES];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self hideProcessHUD];
        if (completion) {
            completion();
        }
    });
}

- (void)showProcessHUDWithProcessValue:(CGFloat)value title:(NSString *)title
{
    MBProgressHUD *hud = nil;
    if ([self isKindOfClass:[UINavigationController class]]) {
        hud = (MBProgressHUD *)[self.view viewWithTag:386];
        if (!hud) {
            hud = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:hud];
            hud.tag = 386;
            hud.mode = MBProgressHUDModeAnnularDeterminate;
            hud.delegate = self;
            [hud show:YES];
        }
    }
    else if(self.navigationController){
        hud = (MBProgressHUD *)[self.navigationController.view viewWithTag:386];
        if (!hud) {
            hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:hud];
            hud.tag = 386;
            hud.mode = MBProgressHUDModeAnnularDeterminate;
            hud.delegate = self;
            [hud show:YES];
        }
    }
    if (value<0) {
        hud.mode = MBProgressHUDModeIndeterminate;
        hud.labelText = title;
        value = 0;
    }
    else {
        hud.mode = MBProgressHUDModeAnnularDeterminate;
        NSInteger percentage = value*100;
        hud.labelText = [NSString stringWithFormat:@"%@ %ld%%",title,(long)percentage];
    }
    hud.progress = value;
    
//    if (value - 0.99 > 0) {
//        [self hideProcessHUD];
//        if (completeBlock) {
//            completeBlock();
//        }
//    }
}

- (void)hideProcessHUD
{
    //隐藏self.view的HUD
    NSArray *HUDArr1 = [MBProgressHUD allHUDsForView:self.view];
    if (HUDArr1.count != 0) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }
    //隐藏self.navigationController.view的HUD
    NSArray *HUDArr2 = [MBProgressHUD allHUDsForView:self.navigationController.view];
    if (HUDArr2.count != 0) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }
    
    /*PS:可能需要扩展隐藏其他View的HUD*/
    
//    if ([self isKindOfClass:[UINavigationController class]]) {
//        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
//    }
//    else if(self.navigationController){
//        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
//    }
}

+ (id)viewControllerWithStoryBoard:(NSString *)sbName identify:(NSString *)identify
{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:sbName bundle:nil];
    if (sb) {
        if (identify) {
            return [sb instantiateViewControllerWithIdentifier:identify];
        }
        return [sb instantiateInitialViewController];
    }
    return nil;
}

/**
 *    是否为正在显示的viewController
 *
 *    @return <#return value description#>
 */
- (BOOL)isCurrentViewController
{
    BOOL bRet = YES;
    do{
        if (self.presentedViewController) {//如果有弹出任何viewController，则不在最上面
            bRet = NO;
            break;
        }
        if (self.navigationController && self.navigationController.topViewController!=self) {
            bRet = NO;
            break;
        }
        
    }while (0);
    
    return bRet;
}

@end

#pragma mark UINavigationController(Replace)
@implementation UINavigationController(Replace)

- (void)replaceCurrViewControllerWithViewCtl:(UIViewController *)viewCtl animate:(BOOL)animate
{
    NSMutableArray *viewCtls = [[self viewControllers] mutableCopy];
    [viewCtls removeLastObject];
    [viewCtls addObject:viewCtl];
    [self setViewControllers:viewCtls animated:animate];
}

@end
